package cn.com.homeyoda.aimate.aihealth.ui.health;

import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivitySportPlanDetailsBinding;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekCourseAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekSelectAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.viewModel.SportPlanViewModel;
import cn.com.homeyoda.aimate.aihealth.views.CenterDialog;
import cn.com.homeyoda.aimate.aihealth.views.SpaceItemDecoration;

/**
 * 运动计划详情
 */
public class SportPlanDetailsActivity extends BaseActivity<ActivitySportPlanDetailsBinding, SportPlanViewModel> {

    private WeekSelectAdapter weekSelectAdapter;
    private WeekCourseAdapter weekCourseAdapter;

    private String planId;
    private String faceId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (getIntent() != null && getIntent().getExtras() != null) {
            planId = getIntent().getExtras().getString("planId");
            faceId = getIntent().getExtras().getString("faceId");
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public SportPlanViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(SportPlanViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        initView();
        viewModel.initWeek();
        viewModel.initPlanDetails("", planId, viewModel.weekList.getValue().get(viewModel.mWeek.getValue()).getDate());
    }


    private void joinPlan() {
        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                // .setTheme(R.style.ThemeOverlay_App_DatePicker)
                .build();

// 显示日期选择器
        datePicker.show(getSupportFragmentManager(), "DATE_PICKER");

// 处理选择结果
        datePicker.addOnPositiveButtonClickListener(selection -> {
            // 选择的日期时间戳（UTC毫秒）
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            calendar.setTimeInMillis(selection);

            SimpleDateFormat format = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String selectedDate = format.format(calendar.getTime());
                viewModel.joinPlan(faceId, planId, selectedDate, viewModel.planDetailsLiveData.getValue());
            }
        });
    }

    private void caclePlan() {
        CenterDialog dialog = new CenterDialog(this, getResources().getString(R.string.cacle_plan_message), new CenterDialog.SureClickListener() {
            @Override
            public void sureClick() {
                viewModel.unJoinPlan(faceId, planId);
            }
        });

        dialog.show();
    }

    private void selectDay() {
        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                // .setTheme(R.style.ThemeOverlay_App_DatePicker)
                .build();

// 显示日期选择器
        datePicker.show(getSupportFragmentManager(), "DATE_PICKER");

// 处理选择结果
        datePicker.addOnPositiveButtonClickListener(selection -> {
            // 选择的日期时间戳（UTC毫秒）
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            calendar.setTimeInMillis(selection);
            viewModel.selectNewWeek(calendar);

            SimpleDateFormat format = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String selectedDate = format.format(calendar.getTime());
                viewModel.initPlanDetails("",
                        UserInfoManager.getInstance().selfSportPlan.getPlanId(), selectedDate);
            }

        });
    }

    private void initView() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.tvTitle.setText(R.string.stort_plan);

        updateJoinPlanButton();
        binding.joinPlan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!UserInfoManager.getInstance().isJoinPlan()
                        || !UserInfoManager.getInstance().selfSportPlan.getPlanId().equals(planId)
                ) {

                    if (UserInfoManager.getInstance().isJoinPlan()) {
                        // 当前已经加入计划了，提示一下
                        CenterDialog dialog = new CenterDialog(SportPlanDetailsActivity.this,
                                getResources().getString(R.string.join_sport_plan_error), new CenterDialog.SureClickListener() {
                            @Override
                            public void sureClick() {
                                joinPlan();
                            }
                        });

                        dialog.show();
                    } else {
                        joinPlan();
                    }


                } else {
                    caclePlan();
                }
            }
        });

        binding.btnDateSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectDay();
            }
        });

        initWeekView();

    }

    private void initWeekView() {
        weekSelectAdapter = new WeekSelectAdapter(R.layout.item_week_select, new ArrayList<>(), this);
        binding.rvWeek.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        binding.rvWeek.addItemDecoration(new SpaceItemDecoration(0, 0, 10, 0));
        binding.rvWeek.setAdapter(weekSelectAdapter);

        weekSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                viewModel.setWeek("", planId, position);
            }
        });


        weekCourseAdapter = new WeekCourseAdapter(R.layout.item_week_couse_select, new ArrayList(), this);
        binding.rvCourse.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        binding.rvCourse.addItemDecoration(new SpaceItemDecoration(0, 0, 10, 0));
        binding.rvCourse.setAdapter(weekCourseAdapter);

        weekCourseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("videoUrl", weekCourseAdapter.getData().get(position).getVideoUrl());
                startActivity(VideoPlayActivity.class, bundle);
            }
        });
    }


    /**
     * 加入计划和取消计划按钮UI更新
     */
    private void updateJoinPlanButton() {
        if (UserInfoManager.getInstance().isJoinPlan() &&
                UserInfoManager.getInstance().selfSportPlan.getPlanId().equals(planId)
        ) {
            binding.joinPlan.setBackgroundResource(R.mipmap.bg_cacle_plan);
            binding.joinPlan.setText(R.string.cacle_plan);
        } else {
            binding.joinPlan.setText(R.string.join_plan);
            binding.joinPlan.setBackgroundResource(R.mipmap.bg_join_plan);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public String decodeBase64ToString(String base64String) {
        byte[] decodedBytes = Base64.decode(base64String, Base64.DEFAULT);
        return new String(decodedBytes, StandardCharsets.UTF_8);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.planDetailsLiveData.observe(this, dataBean -> {
            binding.tvTrainName.setText(dataBean.getPlanName());
            binding.tvIntro.setText(dataBean.getIntro());
            binding.tvTitle1.setText(dataBean.getTitle());
            binding.tvMessage.loadDataWithBaseURL(null, decodeBase64ToString(dataBean.getDetailMsg()), "text/html", "UTF-8", null);
            weekCourseAdapter.setNewData(dataBean.getSubjectList());
        });

        viewModel.weekList.observe(this, weeks -> {
            if (weekSelectAdapter != null) {
                weekSelectAdapter.setNewData(weeks);
            }
        });

        viewModel.mWeek.observe(this, mWeek -> {
            weekSelectAdapter.setSelectPosition(mWeek);
        });

        viewModel.joinPlanStateLiveData.observe(this, state -> {
            updateJoinPlanButton();
        });

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_sport_plan_details;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


}
